#!/bin/sh /etc/rc.common
START=99

config_qbittorrent()
{
	local download_dir
	local port
	config_get download_dir $1 download_dir
	config_get port $1 port
	if [ -f $2/qBittorrent/config/qBittorrent.conf ]; then
		sed -i  's/WebUI\\Port=[0-9]*/WebUI\\Port='"$port"'/g' $2/qBittorrent/config/qBittorrent.conf
		sed -i  's/Downloads\\SavePath=[a-z,/]*//g' $2/qBittorrent/config/qBittorrent.conf
		echo "Downloads\SavePath=$down" >> $2/qBittorrent/config/qBittorrent.conf
	else
	cat>$2/qBittorrent/config/qBittorrent.conf<<EOF
[AutoRun]
enabled=false
program=

[LegalNotice]
Accepted=true

[Network]
Cookies=@Invalid()

[Preferences]
Downloads\SavePath=$download_dir
General\Locale=zh
WebUI\Port=$port
EOF
	fi
}
	
run_qbittorrent()
{
    local enable
    config_get_bool enable $1 enable
    
    if [ $enable ]; then
        local profile_dir
        config_get profile_dir $1 profile_dir
	config_foreach config_qbittorrent 'Preferences' $profile_dir        
        if [ "$profile_dir" != "" ]; then
        	config_get library_dir $1 library_dir
        	config_get program_dir $1 program_dir
        	export PATH=$PATH:$program_dir
        	export LD_LIBRARY_PATH=$library_dir
            qbittorrent-nox -d --profile=$profile_dir 
        else
            echo "no profile_dir,stop!"
        fi

    fi
}

start()
{
	local profile_path
	config_load 'qbittorrent'
	config_foreach run_qbittorrent 'basic'
}

stop()
{
    killall qbittorrent-nox
    return 0
}
